/**
 * @Description: 防抖函数
 * 防抖原理：一定时间内，只有最后一次操作，再过wait毫秒后才执行函数
 * @Author: Zander
 * @Date: 2023/1/5 12:27
 * @LastEditors: Zander
 * @LastEditTime: 2023/1/5 12:27
 * @param {Function} func 要执行的回调函数
 * @param {Number} wait 延时的时间
 * @param {Boolean} immediate 是否立即执行
 */
function debounce(func, wait = 500, immediate = false) {
  let timeout, args, context, timestamp, result;
  function later() {
    // 据上一次触发时间间隔
    const last = new Date().getTime() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  const debounced = function() {
    context = this;
    args = arguments;
    timestamp = new Date().getTime();
    const callNow = immediate && !timeout;
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait);
    if (callNow) {
      result = func.apply(context, args);
      context = args = null;
    }

    return result;
  }

  debounced.cancel = function() {
    if (timeout) {
      clearTimeout(timeout);
      timeout = null;
    }
  }

  debounced.flush = function() {
    if (timeout) {
      result = func.apply(context, args);
      context = args = null;

      clearTimeout(timeout);
      timeout = null;
    }
  }

  return debounced();
}

debounce.debounce = debounce;

module.exports = debounce;
